package com.schoolET.service.wechat.wechatImpl;

import com.schoolET.entity.Goods;
import com.schoolET.entity.OrderForm;
import com.schoolET.entity.OrderManagement;
import com.schoolET.entity.dto.GoodsInfoDTO;
import com.schoolET.entity.dto.WechatInfoDTO;
import com.schoolET.entity.vo.PurchaseGoodsVO;
import com.schoolET.error.costom.NoBuyException;
import com.schoolET.mapper.GoodsMapper;
import com.schoolET.mapper.OrderFormMapper;
import com.schoolET.mapper.OrderManagementMapper;
import com.schoolET.mapper.WechatMapper;
import com.schoolET.service.wechat.TradeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author: lin
 * @className: TradeService
 * @createTime: 2024-06-12  20:59
 * @description:
 */
@Service
@Slf4j
public class TradeServiceImpl implements TradeService {

    @Resource
    private WechatMapper wechatMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private OrderManagementMapper orderManagementMapper;

    @Resource
    private OrderFormMapper orderFormMapper;

    @Override
    public boolean purchaseOfGoods(PurchaseGoodsVO purchaseGoodsVO, String wechatId) {
        GoodsInfoDTO goodsInfoDTO = goodsMapper.selectGoodsById(purchaseGoodsVO.getGoodsId());
        if (goodsInfoDTO == null) {
            throw new NoBuyException();
        }
        WechatInfoDTO wechatInfoDTO = wechatMapper.selectByOpenId(wechatId);
        if (goodsInfoDTO.getWechatId().equals(wechatInfoDTO.getId())) {
            throw new NoBuyException();
        }
        orderManagementMapper.updateOrderManagementByPurchase(purchaseGoodsVO.getGoodsId(),
                wechatInfoDTO.getId(),
                purchaseGoodsVO.getBuyerAddress(),
                new Date());
        return true;
    }

    @Override
    @Transactional
    public boolean orderOver(Integer id, String wechatId) {
        WechatInfoDTO wechatInfoDTO = wechatMapper.selectByOpenId(wechatId);
        OrderManagement orderManagement = orderManagementMapper.selectByGoodsId(id);
        Goods goods = goodsMapper.selectGoodsByConfirmId(id);
        orderManagementMapper.updateOrderManagementByConfirm(id, wechatInfoDTO.getId(),new Date());
        OrderForm orderForm = new OrderForm(id,orderManagement.getReleaseId(),
                orderManagement.getBuyerId(),
                goods.getPrice(),
                goods.getPrice()/10,
                (goods.getPrice()-goods.getPrice()/10),goods.getAddress(),orderManagement.getBuyerAddress(),1);
        orderFormMapper.insert(orderForm);
        return true;
    }

    @Override
    public boolean orderEnd(Integer id, String wechatId) {
        WechatInfoDTO wechatInfoDTO = wechatMapper.selectByOpenId(wechatId);
        orderManagementMapper.updateOrderManagementByStop(id, wechatInfoDTO.getId(),new Date());
        return true;
    }
}
